package com.kuang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.common.constant.ProductConstant;
import com.kuang.common.to.SkuHasStockVo;
import com.kuang.common.to.SkuReductionTo;
import com.kuang.common.to.SpuBoundTo;
import com.kuang.common.to.es.SkuEsModel;
import com.kuang.common.utils.PageUtils;
import com.kuang.common.utils.Query;
import com.kuang.common.utils.R;
import com.kuang.gulimall.product.dao.SpuInfoDao;
import com.kuang.gulimall.product.entity.*;
import com.kuang.gulimall.product.feign.CouponFeignService;
import com.kuang.gulimall.product.feign.SearchSaveService;
import com.kuang.gulimall.product.feign.WareFeignService;
import com.kuang.gulimall.product.service.*;
import com.kuang.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    //远程调用查询库存
    @Autowired
    private WareFeignService wareFeignService;

    //远程调用存储到es
    @Autowired
    private SearchSaveService searchSaveService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1，保存spu基本信息 spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        //字段不一样的字段在这里会存在对不齐的问题，所以需要自己设定进去。
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2，保存spu的描述图片 spu_info_desc(id不是自增的，所以还得自己设定一个id)

        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        //用分隔符保存
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3，保存spu的图片集  spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //4，保存spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity Id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(Id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());

        attrValueService.saveProductAttr(collect);

        //5，保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();

        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r1.getCode()==0){
            log.error("远程保存spu积分信息失败");
        }

        //5，保存当前spu对应的所有sku信息
        //sku信息：
        //1,基本信息：sku_info
        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach(item->{
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                //对拷缺少的数据
                //private String skuName;
                //private BigDecimal price;
                //private String skuTitle;
                //private String skuSubtitle
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //这里调用存储方法之后
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();


                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要，返回false就是剔除
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //TODO 没有图片路径的无需保存
                //2,图片集：sku_images
                skuImagesService.saveBatch(imagesEntities);
                //3,销售属性值：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect1 = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect1);
                //4,sku的优惠、满减信息：要跨库到优惠券系统中

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()<=0 && skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode()==0){
                        log.error("远程保存spu优惠信息失败");
                    }
                }


            });
        }



    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //要检查拼接的条件
        //stat
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        //上面要放到括号里的原因是这样可以实现将添加的语句放到括号里。否则就拼接了两条sql
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //上架功能，为ES存储数据模型。
        //组装需要的数据
        //1，查出当前spuid对应的所有sku信息，品牌的名字。
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        //得到了sku列表
        List<Long> skulist = skus.stream().map(Skuid -> {
            return Skuid.getSkuId();
        }).collect(Collectors.toList());
        //聚合ID,为后面的查询做准备
        //封装sku信息
        // TODO 查询当前sku的所有规格属性，可以用来检索的。这些可以在一开始就查出来，避免循环查询
        //这里定义传输过来的属性的值，最下面有个属性列表，这里先创建
        List<SkuEsModel.Attrs> attrs = new ArrayList<>();
        //返回属性实体列表
        List<ProductAttrValueEntity> entities = attrValueService.baseAttrlistforspu(spuId);
        //对属性id进行收集
        List<Long> attrIdlist = entities.stream().map(entitie -> {
            return entitie.getAttrId();
        }).collect(Collectors.toList());

        //选出需要上架的商品
        List<Long> attrfileter =  attrService.selectSearchAttrs(attrIdlist);

        //创建属性id集合
        Set<Long> idSet = new HashSet<>(attrfileter);

        //选出需要拦截的
        List<SkuEsModel.Attrs> fileterList = entities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs2 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs2);
            return attrs2;
        }).collect(Collectors.toList());

        //这里查库存不要分次数查,远程调用方法查询一次
        Map<Long, Boolean> stockMap = null;
        try{
            R<List<com.kuang.common.to.SkuHasStockVo>> skusHasStock = wareFeignService.getSkusHasStock(skulist);
            List<com.kuang.common.to.SkuHasStockVo> testdata = skusHasStock.getData();
            stockMap = skusHasStock.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}",e);
        }

        //1，设计加上泛型  2，直接返回想要的结果 3，自己解析自己要的结果

        Map<Long, Boolean> finalStockMap = stockMap;

        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            //属性对拷
            BeanUtils.copyProperties(sku,esModel);
            //补齐不同的数据
            //skuPrice,skuImg,hasStock,hotScore
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //TODO 远程调用这里的hasStock和hotScore需要查询对应的库存表。
            if (finalStockMap == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }


            //TODO 热度评分，后台功能扩展0
            esModel.setHotScore(0L);


            //TODO 查询品牌和分类的名字信息
//            esModel.setHasStock();
//            esModel.setHotScore();
            //brandName,brandImg,catalogName,List<Attrs> attrs
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            //List<Attrs> : attrId,attrName,attrValue
            //这个信息是重复的，所以应该提出来。一次查询

            //设置检索属性
            esModel.setAttrs(fileterList);



            return esModel;
        }).collect(Collectors.toList());

        //5,将数据发送给远程es保存：gulimall-search
        R r = searchSaveService.productStatusUp(upProducts);
        if (r.getCode()==0){
            //远程调用成功
            //修改当前sku的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.AttrStatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用，接口幂等性问题。重试机制等等
        }


    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;

    }


}